/**
 * 收藏API库
 * @author HalRui
 * @version 1.0.0
 * @description 提供收藏和收藏夹相关的业务逻辑功能，包括收藏管理、收藏夹管理、统计分析等操作
 * @date 2025年9月27日
 */

const Favorites = require('../models/favorites-model');
const Collections = require('../models/collections-model');
const UserInfos = require('../models/userinfos-model');
const Videos = require('../models/videos-model');
const { connectDB } = require('../utils/db');

/**
 * 添加收藏
 * @param {Object} favoriteData - 收藏数据
 * @param {number} favoriteData.userId - 用户ID
 * @param {number} favoriteData.videoId - 视频ID
 * @param {number} [favoriteData.collectionId] - 收藏夹ID，null表示默认收藏夹
 * @returns {Promise<Object>} 收藏信息
 */
async function addFavorite(favoriteData) {
    try {
        await connectDB();
        
        const { userId, videoId, collectionId } = favoriteData;
        
        // 验证必要参数
        if (!userId || !videoId) {
            throw new Error('用户ID和视频ID不能为空');
        }
        
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            throw new Error('用户不存在');
        }
        
        // 验证视频是否存在
        const video = await Videos.findOne({ videoId, isDeleted: false });
        if (!video) {
            throw new Error('视频不存在');
        }
        
        // 如果指定了收藏夹，验证收藏夹是否存在且属于该用户
        if (collectionId) {
            const collection = await Collections.findOne({ 
                collectionId, 
                userId, 
                isDeleted: false 
            });
            if (!collection) {
                throw new Error('收藏夹不存在');
            }
        }
        
        // 添加收藏
        const favorite = await Favorites.addFavorite({
            userId,
            videoId,
            collectionId: collectionId || null
        });
        
        // 更新收藏夹视频数量
        if (collectionId) {
            await Collections.updateVideoCount(collectionId, 1);
        }
        
        // 获取完整的收藏信息
        const favoriteDetail = await getFavoriteDetail(favorite.favoriteId);
        
        return favoriteDetail;
    } catch (error) {
        console.error('添加收藏失败:', error);
        throw error;
    }
}

/**
 * 取消收藏
 * @param {number} userId - 用户ID
 * @param {number} videoId - 视频ID
 * @returns {Promise<Object>} 取消收藏结果
 */
async function removeFavorite(userId, videoId) {
    try {
        await connectDB();
        
        if (!userId || !videoId) {
            throw new Error('用户ID和视频ID不能为空');
        }
        
        // 获取收藏信息（用于更新收藏夹计数）
        const favorite = await Favorites.findOne({ 
            userId, 
            videoId, 
            isDeleted: false 
        });
        
        if (!favorite) {
            throw new Error('收藏记录不存在');
        }
        
        const collectionId = favorite.collectionId;
        
        // 取消收藏
        const result = await Favorites.removeFavorite(userId, videoId);
        
        // 更新收藏夹视频数量
        if (collectionId) {
            await Collections.updateVideoCount(collectionId, -1);
        }
        
        return result;
    } catch (error) {
        console.error('取消收藏失败:', error);
        throw error;
    }
}

/**
 * 检查收藏状态
 * @param {number} userId - 用户ID
 * @param {number} videoId - 视频ID
 * @returns {Promise<Object>} 收藏状态
 */
async function checkFavoriteStatus(userId, videoId) {
    try {
        await connectDB();
        
        if (!userId || !videoId) {
            throw new Error('用户ID和视频ID不能为空');
        }
        
        const status = await Favorites.checkFavoriteStatus(userId, videoId);
        
        return status;
    } catch (error) {
        console.error('检查收藏状态失败:', error);
        throw error;
    }
}

/**
 * 获取用户收藏列表
 * @param {Object} options - 查询选项
 * @param {number} options.userId - 用户ID
 * @param {number} [options.collectionId] - 收藏夹ID
 * @param {number} [options.page=1] - 页码
 * @param {number} [options.limit=20] - 每页数量
 * @returns {Promise<Object>} 收藏列表和分页信息
 */
async function getUserFavorites(options) {
    try {
        await connectDB();
        
        const { userId, collectionId, page = 1, limit = 20 } = options;
        
        if (!userId) {
            throw new Error('用户ID不能为空');
        }
        
        // 获取收藏列表
        const result = await Favorites.getUserFavorites({
            userId,
            collectionId,
            page,
            limit
        });
        
        // 获取视频信息
        const videoIds = result.favorites.map(favorite => favorite.videoId);
        const videos = await Videos.find({ 
            videoId: { $in: videoIds }, 
            isDeleted: false 
        }).lean();
        
        const videoMap = {};
        videos.forEach(video => {
            videoMap[video.videoId] = video;
        });
        
        // 组合收藏和视频信息
        const favoritesWithVideoInfo = result.favorites.map(favorite => {
            const video = videoMap[favorite.videoId];
            return {
                ...favorite,
                video: video ? {
                    videoId: video.videoId,
                    title: video.title,
                    coverImage: video.coverImage,
                    duration: video.duration,
                    viewCount: video.viewCount,
                    likeCount: video.likeCount,
                    createAt: video.createAt
                } : null
            };
        }).filter(item => item.video); // 过滤掉视频不存在的收藏
        
        return {
            favorites: favoritesWithVideoInfo,
            pagination: result.pagination
        };
    } catch (error) {
        console.error('获取用户收藏列表失败:', error);
        throw error;
    }
}

/**
 * 获取收藏详情
 * @param {number} favoriteId - 收藏ID
 * @returns {Promise<Object|null>} 收藏详情
 */
async function getFavoriteDetail(favoriteId) {
    try {
        await connectDB();
        
        if (!favoriteId) {
            throw new Error('收藏ID不能为空');
        }
        
        const favorite = await Favorites.findOne({ 
            favoriteId, 
            isDeleted: false 
        }).lean();
        
        if (!favorite) {
            return null;
        }
        
        // 获取视频信息
        const video = await Videos.findOne({ 
            videoId: favorite.videoId, 
            isDeleted: false 
        }).lean();
        
        // 获取收藏夹信息
        let collection = null;
        if (favorite.collectionId) {
            collection = await Collections.findOne({ 
                collectionId: favorite.collectionId, 
                isDeleted: false 
            }).lean();
        }
        
        return {
            ...favorite,
            video: video ? {
                videoId: video.videoId,
                title: video.title,
                coverImage: video.coverImage,
                duration: video.duration,
                viewCount: video.viewCount,
                likeCount: video.likeCount,
                createAt: video.createAt
            } : null,
            collection: collection ? {
                collectionId: collection.collectionId,
                name: collection.name,
                description: collection.description
            } : null
        };
    } catch (error) {
        console.error('获取收藏详情失败:', error);
        throw error;
    }
}

/**
 * 批量检查收藏状态
 * @param {number} userId - 用户ID
 * @param {number[]} videoIds - 视频ID数组
 * @returns {Promise<Object>} 收藏状态映射
 */
async function batchCheckFavoriteStatus(userId, videoIds) {
    try {
        await connectDB();
        
        if (!userId || !Array.isArray(videoIds)) {
            throw new Error('用户ID和视频ID数组不能为空');
        }
        
        const statusMap = await Favorites.batchCheckFavoriteStatus(userId, videoIds);
        
        return statusMap;
    } catch (error) {
        console.error('批量检查收藏状态失败:', error);
        throw error;
    }
}

/**
 * 移动收藏到其他收藏夹
 * @param {number} favoriteId - 收藏ID
 * @param {number} userId - 用户ID
 * @param {number} newCollectionId - 新收藏夹ID
 * @returns {Promise<Object>} 移动结果
 */
async function moveFavorite(favoriteId, userId, newCollectionId) {
    try {
        await connectDB();
        
        if (!favoriteId || !userId) {
            throw new Error('收藏ID和用户ID不能为空');
        }
        
        // 获取原收藏信息
        const originalFavorite = await Favorites.findOne({ 
            favoriteId, 
            userId, 
            isDeleted: false 
        });
        
        if (!originalFavorite) {
            throw new Error('收藏记录不存在');
        }
        
        const oldCollectionId = originalFavorite.collectionId;
        
        // 如果指定了新收藏夹，验证收藏夹是否存在
        if (newCollectionId) {
            const collection = await Collections.findOne({ 
                collectionId: newCollectionId, 
                userId, 
                isDeleted: false 
            });
            if (!collection) {
                throw new Error('目标收藏夹不存在');
            }
        }
        
        // 移动收藏
        const favorite = await Favorites.moveFavorite(favoriteId, userId, newCollectionId);
        
        // 更新收藏夹视频数量
        if (oldCollectionId) {
            await Collections.updateVideoCount(oldCollectionId, -1);
        }
        if (newCollectionId) {
            await Collections.updateVideoCount(newCollectionId, 1);
        }
        
        return favorite;
    } catch (error) {
        console.error('移动收藏失败:', error);
        throw error;
    }
}

/**
 * 获取收藏统计
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 收藏统计信息
 */
async function getFavoriteStats(userId) {
    try {
        await connectDB();
        
        if (!userId) {
            throw new Error('用户ID不能为空');
        }
        
        const stats = await Favorites.getFavoriteStats(userId);
        
        return stats;
    } catch (error) {
        console.error('获取收藏统计失败:', error);
        throw error;
    }
}

// 收藏夹相关API

/**
 * 创建收藏夹
 * @param {Object} collectionData - 收藏夹数据
 * @param {number} collectionData.userId - 用户ID
 * @param {string} collectionData.name - 收藏夹名称
 * @param {string} [collectionData.description] - 收藏夹描述
 * @param {string} [collectionData.privacy='private'] - 隐私设置
 * @returns {Promise<Object>} 创建的收藏夹信息
 */
async function createCollection(collectionData) {
    try {
        await connectDB();
        
        const collection = await Collections.createCollection(collectionData);
        
        return collection.getSafeJSON();
    } catch (error) {
        console.error('创建收藏夹失败:', error);
        throw error;
    }
}

/**
 * 获取用户收藏夹列表
 * @param {Object} options - 查询选项
 * @param {number} options.userId - 用户ID
 * @param {number} [options.viewerId] - 查看者ID
 * @param {number} [options.page=1] - 页码
 * @param {number} [options.limit=20] - 每页数量
 * @returns {Promise<Object>} 收藏夹列表和分页信息
 */
async function getUserCollections(options) {
    try {
        await connectDB();
        
        const result = await Collections.getUserCollections(options);
        
        return result;
    } catch (error) {
        console.error('获取用户收藏夹列表失败:', error);
        throw error;
    }
}

/**
 * 获取收藏夹详情
 * @param {number} collectionId - 收藏夹ID
 * @param {number} viewerId - 查看者ID
 * @returns {Promise<Object|null>} 收藏夹详情
 */
async function getCollectionDetail(collectionId, viewerId) {
    try {
        await connectDB();
        
        const collection = await Collections.getCollectionDetail(collectionId, viewerId);
        
        return collection;
    } catch (error) {
        console.error('获取收藏夹详情失败:', error);
        throw error;
    }
}

/**
 * 更新收藏夹
 * @param {number} collectionId - 收藏夹ID
 * @param {number} userId - 用户ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<Object>} 更新后的收藏夹信息
 */
async function updateCollection(collectionId, userId, updateData) {
    try {
        await connectDB();
        
        const collection = await Collections.updateCollection(collectionId, userId, updateData);
        
        return collection.getSafeJSON();
    } catch (error) {
        console.error('更新收藏夹失败:', error);
        throw error;
    }
}

/**
 * 删除收藏夹
 * @param {number} collectionId - 收藏夹ID
 * @param {number} userId - 用户ID
 * @returns {Promise<Object>} 删除结果
 */
async function deleteCollection(collectionId, userId) {
    try {
        await connectDB();
        
        const result = await Collections.deleteCollection(collectionId, userId);
        
        return result;
    } catch (error) {
        console.error('删除收藏夹失败:', error);
        throw error;
    }
}

/**
 * 获取热门公开收藏夹
 * @param {Object} options - 查询选项
 * @param {number} [options.limit=20] - 数量限制
 * @param {string} [options.timeRange='7d'] - 时间范围
 * @returns {Promise<Array>} 热门收藏夹列表
 */
async function getPopularCollections(options) {
    try {
        await connectDB();
        
        const collections = await Collections.getPopularCollections(options);
        
        return collections;
    } catch (error) {
        console.error('获取热门收藏夹失败:', error);
        throw error;
    }
}

module.exports = {
    // 收藏相关
    addFavorite,
    removeFavorite,
    checkFavoriteStatus,
    getUserFavorites,
    getFavoriteDetail,
    batchCheckFavoriteStatus,
    moveFavorite,
    getFavoriteStats,
    
    // 收藏夹相关
    createCollection,
    getUserCollections,
    getCollectionDetail,
    updateCollection,
    deleteCollection,
    getPopularCollections
};